package com.engine.dffd.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.addons.common.constant.ResultCode;
import com.engine.addons.common.entity.ResultMsg;
import com.engine.addons.common.util.FastJsonUtil;
import com.engine.addons.common.util.LogUtil;
import com.engine.addons.common.util.PropertiesUtil;
import com.engine.addons.common.util.StringUtil;
import com.engine.addons.init.config.constant.ValueType;
import com.engine.addons.init.dataProcess.entity.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DffdSyncDataUtil {

    private static final LogUtil LOG = new LogUtil(DffdSyncDataUtil.class);


    public static ResultMsg<String> callSync(String sendJson, String type) {

        ResultMsg<String> resultMsg = new ResultMsg<>(ResultCode.NotFound);

        try {

            PropertiesUtil prop = new PropertiesUtil();
            String baseUrl = prop.readProperty("dffd.url");
            String syncUrl ="";
            if("ypcsfqSync".equals(type)) {// 叶片测算发起
                syncUrl = prop.readProperty("ypcsfs.url");
            }else if("ypmbcbfqSync".equals(type)) {// 叶片目标成本发起
                syncUrl = prop.readProperty("ypmbcbfq.url");
            }
            LOG.writeSystemLog("同步发送：" + sendJson);
            LOG.writeSystemLog("同步URL：" + baseUrl + syncUrl);
            String resStr = HttpRequest.post(baseUrl + syncUrl).header("Content-Type", "application/json").body(sendJson).execute().body();
            LOG.writeSystemLog("同步返回：" + resStr);
            if (StringUtil.isNull(resStr)) {
                resultMsg.setText("同步失败，返回为空");
                return resultMsg;
            }

            JSONObject resJson = JSONObject.parseObject(resStr);
            String status = resJson.getString("STATUS");
            if (!"S".equals(status)) {
                resultMsg.setText("同步失败:"  + resJson.getString("message"));
                return resultMsg;
            }

            resultMsg.setCode(ResultCode.SUCCESS.getCode());
            resultMsg.setObject(resJson.getString("DATA"));
            return resultMsg;

        } catch (Exception e) {
            LOG.writeSystemLog("同步", e);
            resultMsg.setText("同步:" + e.getMessage());
            return resultMsg;
        }

    }



    public static JSONObject covertTableToJson(DataFormTable dataFormTable) {

        JSONObject resJson = new JSONObject(true);

        //主表
        MainTable main = dataFormTable.getFormTableList().get(0).getMaintableProcessData().get(0);
        List<Field> mainRow = main.getRow().getFields();
        for (Field mainField : mainRow) {
            if (mainField.getType() == null || !mainField.getType().equals(ValueType.VIRTUAL)) {
                if("ERDAT".equals(mainField.getName()) || "AEDAT".equals(mainField.getName())){
                    Object value = mainField.getValue();
                    if(value != null){
                        value = value.toString().replaceAll("-","");
                    }
                    FastJsonUtil.setValue(resJson, mainField.getName(), value);
                }else {
                    FastJsonUtil.setValue(resJson, mainField.getName(), mainField.getValue());
                }
            }
        }

        //明细表
        List<DetailTable> detailtableTemp = dataFormTable.getFormTableList().get(0).getDetailtable();
        LOG.writeSystemLog("明细表个数："+detailtableTemp.size());
        if (detailtableTemp != null && detailtableTemp.size() > 0) {

            //先根据明细表输出名合并明细表内容
            Map<String, List<Row>> dataMapList = new HashMap<>();
            for (DetailTable detailTable : detailtableTemp) {

                String outputAlias = detailTable.getOutputAlias();
                LOG.writeSystemLog("outputAlias："+outputAlias);
                if (dataMapList.containsKey(outputAlias)) {
                    dataMapList.get(outputAlias).addAll(detailTable.getRows());
                } else {
                    dataMapList.put(outputAlias, detailTable.getRows());
                }
            }

            //循环明细表
            for (Map.Entry<String, List<Row>> entry : dataMapList.entrySet()) {

                List<Row> dataRows = entry.getValue();

                String outputAlias = entry.getKey();
                JSONArray detailJson = new JSONArray();

                for (Row dataRow : dataRows) {

                    JSONObject detailTemp = new JSONObject(true);

                    List<Field> fieldList = dataRow.getFields();
                    for (Field field : fieldList) {
                        if (field.getType() == null || !field.getType().equals(ValueType.VIRTUAL)) {

                            String fname = field.getName();
                            FastJsonUtil.setValue(detailTemp, fname, field.getValue());
                        }
                    }

                    detailJson.add(detailTemp);
                }

                FastJsonUtil.setValue(resJson, outputAlias, detailJson);

            }
        }
        LOG.writeSystemLog("resJson："+resJson);
        return resJson;
    }
}
